﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using SimpleWeather.BusinessEntities;
using SimpleWeather.DataControllers;
using SimpleWeather.WeatherService;
using StyleMVVM.DependencyInjection;
using StyleMVVM.LanguageExtensions;
using StyleMVVM.ViewModel;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace SimpleWeather.ViewModels
{
	public class CityOverviewPageViewModel : PageViewModel
	{
		#region Private Fields
		private DelegateCommand backCommand;
		private EventCommand itemClickCommand;
		private EventCommand headerClickedCommand;
		private CollectionViewSource cities;
		private bool isBusy;
		#endregion

		#region Imports

		[Import]
		public IWeatherServiceController DataController { get; set; }

		#endregion

		#region public Members

		[ActivationComplete]
		public async void Activated()
		{
			IsBusy = true;

			try
			{
				Cities.Source = await DataController.GetWeatherForAllCities();
			}
			catch (Exception exp)
			{
				Log.Error("Exception thrown while fetching weather",exp);
			}
			finally
			{
				IsBusy = false;
			}
		}
		
		public CollectionViewSource Cities
		{
			get
			{
				if (cities == null)
				{
					// I am creating the CollectionViewSource in code because 
					// if its done in the XMAL it won't work at design time ....
					// really not very cool but I want design time data baby!
					cities = new CollectionViewSource();

					cities.IsSourceGrouped = true;
					cities.ItemsPath = new PropertyPath("ExtendedForecast.ForecastResult");
				}

				return cities;
			}
		}
		
		#region Commands
		public ICommand BackCommand
		{
			get
			{
				if (backCommand == null)
				{
					backCommand = new DelegateCommand((x) => Navigation.GoBack());
				}

				return backCommand;
			}
		}

		public bool IsBusy
		{
			get { return isBusy; }
			set { SetProperty(ref isBusy, value); }
		}

		#endregion

		#endregion


		public void ItemClickHandler(FrameworkElement sender, ItemClickEventArgs clickEventArgs)
		{
			if (clickEventArgs.ClickedItem is CompleteDayForecast)
			{
				CompleteDayForecast forecast = clickEventArgs.ClickedItem as CompleteDayForecast;

				string navigationParameter =
					DataController.GetUniqueForecastID(forecast);

				Navigation.Navigate("ForecastDetailsPage", navigationParameter);
			}
		}

		public void HeaderClickHandler(CityWeather dataContext)
		{
			
		}
	}
}
